#!/bin/sh
#
# $OpenBSD: cupsd.rc,v 1.24 2016/04/12 06:45:36 ajacoutot Exp $

daemon="${TRUEPREFIX}/sbin/cupsd"

. /etc/rc.d/rc.subr

pexp="${daemon} .*"

_lpfiles="/usr/bin/lpq /usr/bin/lpr /usr/bin/lprm /usr/sbin/lpc \
	  /usr/sbin/lpd /usr/share/man/man1/lpq.1 /usr/share/man/man1/lpr.1 \
	  /usr/share/man/man1/lprm.1 /usr/share/man/man8/lpc.8 \
	  /usr/share/man/man8/lpd.8"

rc_pre() {
	# rcexec is needed if openfiles limits are bumped and cupsd(8)
	# runs in debug mode to prevent MaxClients warnings in logs
	${rcexec} "${daemon} ${daemon_flags} -t" || return 1
	[ -e /dev/lpt0 ] && chown _cups /dev/lp[a,t][0-2]
	# XXX cups-driverd(8) can crash when setting up a printer driver
	rm -f /var/cache/cups/*

	if [ -e /usr/sbin/lpd.pre-cups -a ! -f /usr/sbin/lpd -a -L /usr/sbin/lpc ]; then
		return
	elif [ ! -e /usr/sbin/lpd ]; then
		return
	else
		for i in ${_lpfiles}; do
			if [ -f $i -a ! -L $i ]; then
				mv -f $i $i.pre-cups
			fi
		done
	fi
	if [ -e /etc/printcap ]; then
		if [ ! -e /etc/printcap.pre-cups ]; then
			mv /etc/printcap /etc/printcap.pre-cups
			ln -s ${SYSCONFDIR}/cups/printcap /etc/printcap
			chmod -h 0644 /etc/printcap
		fi
	else
		ln -s ${SYSCONFDIR}/cups/printcap /etc/printcap
		chmod -h 0644 /etc/printcap
	fi
	for i in lpq lpr lprm; do
		rm -f /usr/bin/$i
		ln -s ${TRUEPREFIX}/bin/$i /usr/bin/$i
	done
	rm -f /usr/sbin/lpc
	ln -s ${TRUEPREFIX}/sbin/lpc /usr/sbin/lpc
}

rc_post() {
	if [ ! -L /usr/sbin/lpc ]; then
		return
	else
		for i in lpq lpr lprm; do
			rm -f /usr/bin/$i
		done

		rm -f /usr/sbin/lpc

		if [ ! -e /usr/sbin/lpd.pre-cups ]; then
			return
		else
			if [ -L /etc/printcap ]; then
				rm /etc/printcap
			fi
			for i in ${_lpfiles} /etc/printcap; do
				if [ -e $i.pre-cups ]; then
					mv -f $i.pre-cups $i
				fi
			done
		fi
	fi

	[ -e /dev/lpt0 ] && chown root /dev/lp[a,t][0-2]
}

rc_cmd $1
